package my.diplom.util;

import org.apache.log4j.Logger;

import javax.servlet.ServletContext;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.io.InputStream;
import java.io.IOException;

import com.sun.mail.smtp.SMTPTransport;


/**
 * Created by IntelliJ IDEA.
 * User: gb
 * Date: 18.12.2009
 * Time: 0:17:37
 * To change this template use File | Settings | File Templates.
 */
public class MailUtil {


    private static final Logger log = Logger.getLogger(MailUtil.class);
    private static final String SMTP_SERVER = "mail.smtp.host";
    private static final String TRANSPORT = "smtp";
    private static final String USER = "mail.user";
    private static final String PASSW0RD = "mail.password";
    private static final String FROM = "mail.from";


    public static void sendMail(ServletContext context, String to, String subject, String body) throws NoSuchProviderException {

        Properties properties = new Properties();

        try {
            InputStream inputStream = context.getResourceAsStream("/WEB-INF/classes/mail.properties");
            properties.load(inputStream);
        } catch (IOException e) {
            log.error("Erorr get property file", e);
        }

        Session session = Session.getDefaultInstance(properties);
        
        MimeMessage message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(properties.getProperty(FROM)));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);
            message.setSubject(subject);
            message.setText(body, "UTF-8");

            String smtp = properties.getProperty(SMTP_SERVER);
            //System.out.println("smtp = " + smtp);
            String user = properties.getProperty(USER);
            //System.out.println("user = " + user);
            String pass = properties.getProperty(PASSW0RD);
            //System.out.println("pass = " + pass);

            SMTPTransport t = (SMTPTransport) session.getTransport(TRANSPORT);
            t.connect(smtp, user, pass);
            t.sendMessage(message, message.getAllRecipients());
            log.debug("Send email to " + to + " from " + properties.getProperty(FROM) + " subject " + subject + " message " + body);

        } catch (MessagingException e) {
            log.error(e);
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

}
